﻿using BlogModels;
using BlogWeb.Filters;
using BlogWeb.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using X.PagedList; //分页功能

namespace BlogWeb.Controllers
{
    public class BlogController : Controller
    {
        private BlogsDbContext db = new BlogsDbContext();
        // GET: Blog Seach
        [Admin]
        public async Task<ActionResult> Index(int page=1)
        {           
            const int pageSize = 20;//设置每一页显示博客条数的分页常量
            //OrderByDescending 以某一列降序排序
            //ToPagedListAsync(page, pageSize) page当前页，这个需要下载X.PagedList程序集
            var blogs = db.Blogs.OrderByDescending(b => b.AddTime).ToPagedListAsync(page, pageSize);
            return View(await blogs);
        }
        [Admin]
        public async Task<ActionResult> Seach(int page=1)
        {
            HttpCookie cookie = Request.Cookies["Seach"]; //获取名字为Seach的cookie对象
            string str = cookie["SeachStr"].ToString(); //获取这个cookie对象中的SeachStr的值
            const int pageSize = 20;
            var alist = db.Blogs.Where(b => b.Title.IndexOf(str) != -1).OrderByDescending(b => b.AddTime).ToPagedListAsync(page, pageSize);
            if (alist == null)
            {
                return RedirectToAction("Index");
            }            
            return View(await alist);
        }
        [Admin]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Seach() //博客列表Index 页面提交到这个Action方法
        {
            string s = Request.Form["seach"].ToString(); // 获取查询请求输入的关键字符串
            HttpCookie cookie = new HttpCookie("Seach"); //创建一个名字为Seach的cookie对象
            cookie.Values.Set("SeachStr", s); //给这个cookie对象添加键值对 "SeachStr" ： s
            Response.SetCookie(cookie); //将这个cookie写到请求的客户端，以备下次使用
            const int pageSize = 20; //设置每一页显示博客条数的分页常量
            int page = 1; //初始也是第一页
            //IndexOf（s）方法： 查询某字符串中是否包含参数中的字符串，不包含返回-1，包好则返回所在位置
            var alist = db.Blogs.Where(b => b.Title.IndexOf(s) != -1 ).OrderByDescending(b => b.AddTime).ToPagedListAsync(page, pageSize);
            return View(await alist);
        }
        // GET: Blog
        [Admin]
        public ActionResult Create()
        {
            return View();
        }
        [Admin]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public async Task<ActionResult> Create([Bind(Include = "Title,PicTitle,Content")]BlogView blog)
        {
            Blog bg = new Blog
            {
                AddTime = DateTime.Now,
                Title = blog.Title,
                Content = blog.Content,
                PicTitle = blog.PicTitle
            };
            db.Blogs.Add(bg);            
            int i = await db.SaveChangesAsync();
            if (i == 1)
            {
                Response.Write("<script>alert('博客添加成功！');</script>");
                return RedirectToAction("Index");
            }
            else
            {
                Response.Write("<script>alert('博客添加失败！');</script>");
            }
            
            return View(blog);
        }
        [Admin]
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Blog blog = await db.Blogs.FindAsync(id);
            if (blog == null)
            {
                return HttpNotFound();
            }

            return View(blog);
        }
        [Admin]
        // GET: Logs/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Blog blog = await db.Blogs.FindAsync(id);
            if (blog == null)
            {
                return HttpNotFound();
            }           
            return View(blog);
        }
        // POST: Logs/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [Admin]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public async Task<ActionResult> Edit([Bind(Include = "Id,Title,PicTitle,Content,AddTime,EditTime")] Blog blog)
        {
            if (ModelState.IsValid)
            {
                blog.EditTime = DateTime.Now;
                db.Entry(blog).State = EntityState.Modified;
                await db.SaveChangesAsync();
                Response.Write("<script>alert('修改成功！');</script>");
                return RedirectToAction("Index");
            }           
            return View(blog);
        }
        // GET: Logs/Delete/5
        [Admin]
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Blog blog = await db.Blogs.FindAsync(id);
            if (blog == null)
            {
                return HttpNotFound();
            }
            return View(blog);
        }
        /*相册上传图片，批量上传*/
        public ActionResult Uploadimg()
        {
            return View();
        }
        [HttpPost]
        [ActionName("Uploadimg")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Upload([Bind(Include = "Title,PicUrls,AddTime")]PicView picView)
        {
            if (ModelState.IsValid)
            {
               string[] pic_src = picView.PicUrls.Split(',');
               foreach (var item in pic_src)
               {
                    Picture pic = new Picture { Title = picView.Title, PicUrl = item, AddTime = DateTime.Now };
                    db.Pictures.Add(pic);
               }
                await db.SaveChangesAsync();
                Response.Write("<script>alert('上传照片成功！');</script>");
                return RedirectToAction("Index");
            }
            return View(picView);
        }

        public ActionResult Loadimg()
        {
            return View();
        }
        [HttpPost]
        [ActionName("Loadimg")]
        public ActionResult Img()
        {
            string[] url = Request.Params.GetValues("picsrc");
            foreach (var item in url)
            {
                Response.Write(item);
            }
            return View();
        }
        // POST: Logs/Delete/5
        [Admin]
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            Blog blog = await db.Blogs.FindAsync(id);
            db.Blogs.Remove(blog);
            await db.SaveChangesAsync();
            return RedirectToAction("Index", "Blog");
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}